//
//  PMineInviteFriendViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/23.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "PMineInviteFriendViewController.h"
#import <WebKit/WebKit.h>

@interface PMineInviteFriendViewController ()<WKNavigationDelegate, WKUIDelegate>
{
    WKWebView *webView;
}
@property (nonatomic, strong) UIProgressView *progressView;
@end

@implementation PMineInviteFriendViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.navigationItem.title = @"扫码邀请";
    
    webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height)];
//    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.btpin.com/h5/user/invite_act?app_version=%@&token=%@", [UIToolsControl getVersionAndBuild], UD_GetOForK(isToken)]]]];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    webView.navigationDelegate = self;
    webView.UIDelegate = self;
    webView.allowsBackForwardNavigationGestures = YES;
    [self.view addSubview:webView];
    
    //TODO:kvo监听，获得页面title和加载进度值
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(nonnull WKNavigationAction *)navigationAction decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler {
    //    1.拦截请求
    NSString *urlString = [navigationAction.request.URL absoluteString];
//    if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
//        跳转别的应用如系统浏览器 对于跨域，需要手动跳转
//        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
//        // 不允许web内跳转
//        decisionHandler(WKNavigationActionPolicyCancel);
//    } else
    if ([urlString containsString:@"btpin://share?"]) { // 分享 btpin://share?type=1&title=xxx&link=xxx&thumb=xxx&desc=xxx
        decisionHandler(WKNavigationActionPolicyCancel);
        
        NSDictionary *dic = [UIToolsControl getParamsWithUrlString:urlString];
        NSString *type = [UIToolsControl URLDecodedString:dic[@"type"]];
        NSString *title = [UIToolsControl URLDecodedString:dic[@"title"]];
        NSString *link = [UIToolsControl URLDecodedString:dic[@"link"]];
        NSString *thumb = [UIToolsControl URLDecodedString:dic[@"thumb"]];
        NSString *desc = [UIToolsControl URLDecodedString:dic[@"desc"]];
        if ([type isEqualToString:@"1"]) { // 微信好友
            if (![UIToolsControl canOpenWXApp]) {
                SVPHUDError(@"您未安装微信，请先安装");
                return;
            }
            [UIToolsControl wxShareWebURL:link title:title desc:desc thumbUrl:thumb shareType:ShareTypeOfWXHaoyou];
        } else if ([type isEqualToString:@"2"]) { // 朋友圈
            if (![UIToolsControl canOpenWXApp]) {
                SVPHUDError(@"您未安装微信，请先安装");
                return;
            }
             [UIToolsControl wxShareWebURL:link title:title desc:desc thumbUrl:thumb shareType:ShareTypeOfWXPengyouquan];
        } else if ([type isEqualToString:@"3"]) { // QQ
            if (![UIToolsControl canOpenQQApp]) {
                SVPHUDError(@"您未安装QQ，请先安装");
                return;
            }
            [UIToolsControl qqShareWebURL:link title:title desc:desc thumbUrl:thumb shareType:ShareTypeOfQQ];
        } else if ([type isEqualToString:@"4"]) { // QQ空间
            if (![UIToolsControl canOpenQQApp]) {
                SVPHUDError(@"您未安装QQ，请先安装");
                return;
            }
            [UIToolsControl qqShareWebURL:link title:title desc:desc thumbUrl:thumb shareType:ShareTypeOfQQZone];
        }
    } else { // 应用的web内跳转
        decisionHandler (WKNavigationActionPolicyAllow);
    }
    return;//不添加会崩溃
}
- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 2)];
        _progressView.progressTintColor = THEMECOLOR_OF_ORANGE;
        _progressView.backgroundColor = THEMECOLOR_OF_TEXT_cccccc;
        _progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
        [self.view addSubview:self.progressView];
    }
    return _progressView;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (object == webView) {
            self.progressView.progress = webView.estimatedProgress;
            if (self.progressView.progress == 1) {
                __weak __typeof(self)weakSelf = self;
                [UIView animateWithDuration:0.5f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^ {
                    weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
                } completion:^(BOOL finished) {
                    weakSelf.progressView.hidden = YES;
                }];
            }
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else if ([keyPath isEqualToString:@"title"]) {
        if (object == webView) {
            self.navigationItem.title = webView.title;
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = NO;
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view bringSubviewToFront:self.progressView];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = YES;
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    if (error.code==NSURLErrorCancelled) {
        [self webView:webView didFinishNavigation:navigation];
    } else {
        self.progressView.hidden = YES;
    }
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    self.progressView.hidden = YES;
    SVPHUDError(@"加载失败");
}
#pragma mark 移除观察者
- (void)dealloc {
    [webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [webView removeObserver:self forKeyPath:@"title"];
}
- (void)customBackButtonTap {
    if (webView.canGoBack == YES) {
        [webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
